<template>
    <el-card class="container">
        <el-row type="flex" justify="space-between" align="middle" class="custom-banner">
            <el-button v-if="tableData.length !== 0" @click="delPageData" style="margin-bottom: 10px;" plain
                type="danger">删除该表数据</el-button>
            <div class="header">
                <div style="float: left; display: flex; width: 20%;">
                    <img style=" width: 20%; height: 20%;" src="/public/paperAnalysis.png" alt="">
                    <span>试卷分析</span>
                </div>
                <div style="float: right;display: flex;width: 20%;">
                    <img style=" width: 20%; height: 20%;" src="/public/teacher.png" alt="">
                    <span>教师：钟秀玉</span>
                </div>
                <div style="float: right;display: flex;width: 20%;">
                    <img style="   width: 20%; height: 20%;" src="/public/course.png" alt="">
                    <span>课程：数据结构</span>
                </div>
                <div style="float: right;display: flex;width: 20%;">
                    <img style="   width: 20%; height: 20%;" src="/public/class.png" alt="">
                    <span>班级：2203</span>
                </div>
                <div style="float: right;display: flex;width: 20%;">
                    <img style="  width: 20%; height: 20%;" src="/public/academy.png" alt="">
                    <span>学院：计算机学院</span>
                </div>
            </div>
        </el-row>
        <div class="width:100%">
            <!-- <el-table :spanMethod="spanMethod" v-if="tableData.length" :data="tableData" stripe style="width: 100%"
                border="vertical">
                <el-table-column v-for="header in headers" :key="header" :prop="header"
                    :label="header"></el-table-column>
            </el-table> -->
            <div class="table-container">
                <table v-if="tableData.length" class="responsive-table" border="1">
                    <thead>
                        <tr style="background-color: #f2f2f2;">
                            <th v-for="header in headers" :key="header">{{ header }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item, index) in tableData" :key="index">
                            <td v-for="header in headers" :key="header">{{ item[header] }}</td>
                        </tr>
                    </tbody>
                </table>
            </div>





        </div>
        <el-card class="chartsGroup">
            <template v-if="tableData.length" #default>
                <div class="chartsStyle">
                    <div>
                        <Horizontal_columnChart></Horizontal_columnChart>
                    </div>
                    <div>
                        <basicColumnChart></basicColumnChart>
                    </div>
                    <div style="margin-top: 20px;">
                        <pieWithGap></pieWithGap>
                    </div>
                </div>
            </template>
            <el-card>
                <div style="display: flex; justify-content: space-around;height: 70vh;">
                    <div class="leftBox">
                        <p style="color: red;font-style: italic;font-size: 35px;word-break: break-all;">
                            请下载模板，根据模板填写好分数后再上传分数!
                        </p>
                        <el-card style="width: 100%;">
                            <h1 style="height: 5%;font-size: 40px; text-align: center;">下载模板</h1>
                            <div class="btGroup_1"
                                style="height: 10vh; display: flex; justify-content: space-around;align-items: center;">
                                <el-button style="font-size: 30px;border: none;"
                                    @click="getExcelTable('A')">下载A卷模板</el-button>
                                <el-button style="font-size: 30px;border: none;" size="large"
                                    @click="getExcelTable('B')">下载B卷模板</el-button>
                            </div>
                        </el-card>
                    </div>
                    <el-card style="width: 50%; height: 100%;">
                        <h1 style="font-size: 40px; text-align: center;">上传文件</h1>
                        <Analysis_Implement @updateData="handleUpdateData" />
                    </el-card>
                </div>
            </el-card>
        </el-card>
    </el-card>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import Analysis_Implement from './Analysis_Implement.vue'
import pieWithGap from '@/components/pieWithGap.vue'
import Horizontal_columnChart from '@/components/Horizontal_columnChart.vue'
import { autoMakeXlsx_api } from '@/api/target_item_info_input'
const tableData = ref([]);
const headers = ref([]);
import eventBus from '/eventBus';
import basicColumnChart from '@/components/basicColumnChart.vue'
// 组件挂载时尝试从LocalStorage加载数据
onMounted(() => {
    loadFromLocalStorage();
    console.log("tableData.value", tableData.value);
});
import { useRoute } from 'vue-router';
const route = useRoute();
const subId = parseInt(route.params.subId);
const getExcelTable = async (paperType) => {
    try {
        const response = await autoMakeXlsx_api(paperType, subId);
        // 提取buffer数据
        const buffer = response.data.content.data;

        // 创建Blob对象
        const blob = new Blob([new Uint8Array(buffer)], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });

        // 创建一个URL链接，指向响应体的blob
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        // 从响应头中提取文件名，或者如果没有则指定默认的文件名
        const contentDisposition = response.headers['content-disposition'];
        // let filename = 'output.xlsx';
        let filename = `${paperType}卷模板.xlsx`;
        if (contentDisposition) {
            const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            const matches = filenameRegex.exec(contentDisposition);
            if (matches != null && matches[1]) {
                filename = matches[1].replace(/['"]/g, '');
            }
        }
        link.setAttribute('download', filename);

        // 触发下载
        // document.body.appendChild(link);
        // link.click();

        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
    } catch (error) {
        console.error('下载Excel文件失败:', error);
    }
}
const handleUpdateData = (json) => {
    headers.value = json[2];
    const regularData = json.slice(3).map(row => {
        const rowData = {};
        row.forEach((cell, index) => rowData[headers.value[index]] = cell);
        return rowData;
    });
    const specialData = json.slice(0, 2).map(row => {
        const specialRowData = {};
        headers.value.forEach((header, index) => specialRowData[header] = row[index] || '');
        return specialRowData;
    });
    tableData.value = specialData.concat(regularData);

    // 保存数据到 LocalStorage
    saveToLocalStorage();
};
const delPageData = () => {
    localStorage.removeItem('uploadedData');
    eventBus.methods.clearLocalStorage()
    location.reload(true);
}
// 保存数据到LocalStorage
const saveToLocalStorage = () => {
    const dataToStore = {
        headers: headers.value,
        tableData: tableData.value
    };
    localStorage.setItem('uploadedData', JSON.stringify(dataToStore));
};
// 从LocalStorage加载数据
const loadFromLocalStorage = () => {
    const storedData = localStorage.getItem('uploadedData');
    if (storedData) {
        const { headers: storedHeaders, tableData: storedTableData } = JSON.parse(storedData);
        headers.value = storedHeaders;
        tableData.value = storedTableData;
    }
};

</script>

<style lang="scss" scoped>
$table-max-height: 400px; // 表格容器的最大高度

.table-container {
    max-height: $table-max-height;
    overflow-x: auto; // 水平滚动条
    position: relative; // 使得固定列相对于容器定位

    .responsive-table {
        width: auto; // 取消 100% 宽度
        border-collapse: collapse;

        th,
        td {
            padding: 8px;
            border: 1px solid #ddd;
            white-space: nowrap; // 避免内容换行
            overflow: hidden; // 内容溢出隐藏
            text-overflow: ellipsis; // 内容溢出时显示省略号
        }
    }
}

table {
    border-collapse: collapse;
    margin: 25px 0;
    font-size: 0.9em;
    font-family: sans-serif;
    min-width: 400px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
}

th,
td {
    // border: 1px solid black;
    // padding: 8px;
    text-align: center;
    padding: 12px 15px;
    border: 1px solid #dddddd;
}

th {
    background-color: #009879;
    color: #ffffff;
}

tr:hover {
    background-color: #f3f3f3;
}

.wide {
    width: 320px;
}

.container {
    // max-width: 2500px;
    max-width: 100%;

    .custom-banner {
        color: white;
        margin-bottom: 20px;

        .header {
            width: 100%;
            background-color: rgba(95, 214, 217, 0.5);
            background-color: #d9e8fc;
            // background-color: #e5f5fe;
            color: #64748b;
            text-align: center;
            height: 10vh;
            // justify-content: center;
            display: flex;
            // line-height: 100px;
            align-items: center;
            // font-size: 16px;
            // font-size: $global-font-size;
            font-family: Arial, sans-serif;
            border-radius: 5px;
            border-left: 5px solid #60a5fa;
            border-top: none;
            border-right: none;
            border-bottom: none;
            margin-bottom: 10px;
            padding-right: 20px;

            span {
                display: flex;
                // height: 10px;
                // line-height: 10px;
                align-items: center;
            }
        }
    }

    .chartsGroup {
        // margin-top: 30px;
        background-color: #d9e8fc;
        border: 3px solid #60a5fa;

        .chartsStyle {
            overflow-x: auto;
            // max-width: 3000px;
            width: 100%;
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            align-items: center;
        }
    }

    ::v-deep .el-table {
        background-color: #e5f5fe;
        padding: 5px;

        .el-table__cell {
            background-color: #d9e8fc;
        }

        .el-table__th {
            background-color: #075ac7;
        }
    }
}
</style>
